package com.partyjoin.project.module.developmentEvolve.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.partyjoin.project.system.role.domain.Role;
import com.partyjoin.project.system.role.service.IRoleService;
import com.partyjoin.project.system.user.domain.User;
import com.partyjoin.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.partyjoin.common.constant.Constants;
import com.partyjoin.common.utils.DateUtils;
import com.partyjoin.common.utils.security.ShiroUtils;
import com.partyjoin.framework.aspectj.lang.annotation.Log;
import com.partyjoin.framework.aspectj.lang.constant.BusinessType;
import com.partyjoin.project.module.activistEvolve.domain.ActivistEvolve;
import com.partyjoin.project.module.conference.domain.Conference;
import com.partyjoin.project.module.conference.service.IConferenceService;
import com.partyjoin.project.module.developmentEvolve.domain.DevelopmentEvolve;
import com.partyjoin.project.module.developmentEvolve.service.IDevelopmentEvolveService;
import com.partyjoin.project.module.politicalExamine.domain.PoliticalExamine;
import com.partyjoin.project.module.proposer.domain.Proposer;
import com.partyjoin.project.module.proposer.service.IProposerService;
import com.partyjoin.framework.web.controller.BaseController;
import com.partyjoin.framework.web.page.TableDataInfo;
import com.partyjoin.framework.web.domain.AjaxResult;

/**
 * 发展发展对象记录 信息操作处理
 * 
 * @author 莫东林
 * @date 2018-07-19
 */
@Controller
@RequestMapping("/module/developmentEvolve")
public class DevelopmentEvolveController extends BaseController
{
    private String prefix = "module/developmentEvolve";
	
	@Autowired
	private IDevelopmentEvolveService developmentEvolveService;

	@Autowired
	private IUserService userService;

	@Autowired
	private IRoleService roleService;
	
	@Autowired
	private IConferenceService conferenceService;
	
	@Autowired
	private IProposerService proposerService;

	@RequiresPermissions("module:developmentEvolve:view")
	@GetMapping()
	public String developmentEvolve()
	{
	    return prefix + "/developmentEvolve";
	}
	
	/**
	 * 用户上级审核备案时动态获取成员材料
	 * @param userId
	 * @return
	 */
	@PostMapping("/selectUserById")
	@ResponseBody
	public User selectUserById(@RequestParam(name = "userId", required = true) String userId){
		User user = userService.selectProposer(Long.parseLong(userId));
		return user;
	}
	
	/**
	 * 保存备案决议名单
	 */
	@RequiresPermissions("module:developmentEvolve:edit")
	@PostMapping("/saveUserList")
	@ResponseBody
	public AjaxResult saveUserList(DevelopmentEvolve developmentEvolve){
		User user = ShiroUtils.getUser();
		//更新积极分子角色变更为发展对象
		String[] userIds = developmentEvolve.getSuccessList().split(",");
		Long[] roleIds = {Constants.DEVELOPMENT_ROLE_ID};
		if(userIds != null && userIds.length > 0 && !userIds[0].equals("")){
			for(String userId : userIds){
				User users = userService.selectUserById(Long.parseLong(userId));
				Proposer update = proposerService.selectProposerById(users.getUserId());
//				Conference conference = conferenceService.selectConferenceById(developmentEvolve.getConferenceId());
				update.setDevelopmentTime(DateUtils.getNowDate());
				proposerService.updateProposer(update);
				//销毁积极分子角色
				userService.removeUserRole(Long.parseLong(userId), Constants.ACTIVIST_ROLE_ID);
				//更新积极分子角色变更为发展对象
				users.setRoleIds(roleIds);
				userService.insertUserRole(users);
			}
		}
		developmentEvolve.setDisposeTime(DateUtils.getNowDate());
		developmentEvolve.setState(1);
		developmentEvolve.setUpdateBy(user.getUserName());
		developmentEvolve.setUpdateTime(DateUtils.getNowDate());
		if(developmentEvolveService.updateDevelopmentEvolve(developmentEvolve) > 0){
			Conference c = conferenceService.selectConferenceById(developmentEvolve.getConferenceId());
			c.setState(2);
			if(conferenceService.updateConference(c) > 0){
				return success();
			}else{
				return error();
			}
		}else{
			return error();
		}
	}
	
	/**
	 * 根据培养记录编号获取备案成员列表
	 */
	@RequiresPermissions("module:activistEvolve:list")
	@PostMapping("getRecordsUserList")
	@ResponseBody
	public TableDataInfo getRecordsUserList(@RequestParam(name = "id") Integer developmentEvolveId){
		DevelopmentEvolve developmentEvolve = developmentEvolveService.selectDevelopmentEvolveById(developmentEvolveId);
		String[] users = developmentEvolve.getActivistList().split(",");
		List<User> userList = new ArrayList<User>();//存放备案成员
		for(String userId : users){
			User u = userService.selectProposer(Long.parseLong(userId));
			userList.add(u);
		}
		return getDataTable(userList);
	}
	
	/**
	 * 打开备案审核详情界面
	 */
	@RequiresPermissions("module:developmentEvolve:edit")
	@GetMapping("/record/details")
	public String recordDetails(DevelopmentEvolve developmentEvolve, Model model){
		developmentEvolve = developmentEvolveService.selectDevelopmentEvolveById(developmentEvolve.getDevelopmentEvolveId());
//		List<User> recordUserList = new ArrayList<User>();//存放备案名单
//		List<User> recordPassUserList = new ArrayList<User>();//存放备案通过名单
//		List<User> recordNotPassUserList = new ArrayList<User>();//存放备案未通过名单
//		User u = null;//用于开页展示
//		if(developmentEvolve.getActivistList() != null){
//			String[] userList = developmentEvolve.getActivistList().split(",");
//			u = userService.selectProposer(Long.parseLong(userList[0]));
//			System.out.println(u.getProposer().getDevelopmentRecords()+"////////");
//			for(String id : userList){
//				User user = userService.selectUserById(Long.parseLong(id));
//				recordUserList.add(user);
//			}
//		}
//		if(developmentEvolve.getSuccessList() != null){
//			String[] passList = developmentEvolve.getSuccessList().split(",");
//			for(String id : passList){
//				User user = userService.selectUserById(Long.parseLong(id));
//				recordPassUserList.add(user);
//			}
//		}else{
//			recordPassUserList = null;
//		}
//		if(developmentEvolve.getFailList() != null){
//			String[] notPassList = developmentEvolve.getFailList().split(",");
//			for(String id : notPassList){
//				User user = userService.selectUserById(Long.parseLong(id));
//				recordNotPassUserList.add(user);
//			}
//		}else{
//			recordNotPassUserList = null;
//		}
//		model.addAttribute("user", u);
//		model.addAttribute("recordUserList", recordUserList);
//		model.addAttribute("recordPassUserList", recordPassUserList);
//		model.addAttribute("recordNotPassUserList", recordNotPassUserList);
		model.addAttribute("developmentEvolve", developmentEvolve);
//		System.out.println(recordPassUserList);
//		System.out.println(recordNotPassUserList);
		return prefix + "/recordDetails_bak";
	}
	
	/**
	 * 上级备案信息列表
	 */
	@RequiresPermissions("module:developmentEvolve:list")
	@PostMapping("/record/lists")
	@ResponseBody
	public TableDataInfo recordLists(DevelopmentEvolve developmentEvolve){
		startPage();
		//根据登陆用户查询其部门及其子部门备案记录
		if(developmentEvolve.getDeptId() == null){
			developmentEvolve.setDeptId(ShiroUtils.getUserDeptId());
		}
		List<DevelopmentEvolve> list = developmentEvolveService.selectDevelopmentEvolveList(developmentEvolve);
		list = idToNameList(list);
		return getDataTable(list);
	}
	
	/**
	 * 打开上级发展对象备案管理界面
	 */
	@RequiresPermissions("module:developmentEvolve:view")
	@GetMapping("/recordList")
	public String recordList(Model model){
		//获取登陆用户判断管理员角色，若是支部管理员，则无权进行备案操作，只能等待备案
		User user = userService.selectProposer(ShiroUtils.getUserId());
		model.addAttribute("user", user);
		return prefix + "/recordList";
	}
	
	/**
	 * 保存发展对象培养记录
	 */
	@RequiresPermissions("module:developmentEvolve:save")
	@Log(title = "发展对象培养记录", action = BusinessType.SAVE)
	@PostMapping("/save")
	@ResponseBody
	public AjaxResult save(@RequestParam(value = "file") MultipartFile file, DevelopmentEvolve developmentEvolve)
	{
		User user = ShiroUtils.getUser();
		if(upload(developmentEvolve, file, Constants.DEVELOPMENT_ROSTER)){
			developmentEvolve.setDevelopmentRoster("/" + DateUtils.getDate() + "/" + developmentEvolve.getConferenceId() + "/" + file.getOriginalFilename());
		}
		developmentEvolve.setState(0);
		developmentEvolve.setSubmitTime(DateUtils.getNowDate());
		developmentEvolve.setCreateBy(user.getUserName());
		developmentEvolve.setDeptId(ShiroUtils.getUserDeptId());
		developmentEvolve.setCreateTime(DateUtils.getNowDate());
		System.out.println(developmentEvolve);
		if (developmentEvolveService.insertDevelopmentEvolve(developmentEvolve) > 0)
		{
			//会议与发展记录id互绑
			Conference conference = conferenceService.selectConferenceById(developmentEvolve.getConferenceId());
			conference.setState(1);
			if(conferenceService.saveConference(conference) > 0){
				return success();
			}
		}
		return error();
	}
	
	/**
	 * 发展对象详情
	 */
	@RequiresPermissions("module:developmentEvolve:view")
	@GetMapping("/developDetails")
	public String developDetails(User user, Model model){
		user = userService.selectProposer(user.getUserId());
		model.addAttribute("user", user);
		return prefix + "/developDetails";
	}
	
	/**
	 * 查询发展发展对象列表
	 */
	@RequiresPermissions("module:developmentEvolve:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(User user)
	{
		startPage();
		//没部门筛选时,默认根据登录用户所在部门筛选
		if(user.getDeptId() == null){
			user.setDeptId(ShiroUtils.getUserDeptId());
		}
        List<User> list = userService.selectDevelopmentList(user);
		List<Role> roleList = new ArrayList<Role>();
		for(User u : list){
			roleList = roleService.selectRolesByUserId(u.getUserId());
			int i = 0;
			Long[] roles = new Long[10];
			for(Role role : roleList) {
				if(role.isFlag()){
					roles[i]=role.getRoleId();
					i++;
				}

			}
			u.setRoleIds(roles);
		}
		return getDataTable(list);
	}
	
	/**
	 * 新增发展发展对象记录
	 */
	@RequiresPermissions("module:developmentEvolve:add")
	@Log(title = "发展发展对象记录", action = BusinessType.INSERT)
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}

	/**
	 * 修改发展发展对象记录
	 */
	@RequiresPermissions("module:developmentEvolve:edit")
	@Log(title = "发展发展对象记录", action = BusinessType.UPDATE)
	@GetMapping("/edit/{developmentEvolveId}")
	public String edit(@PathVariable("developmentEvolveId") Integer developmentEvolveId, Model model)
	{
		DevelopmentEvolve developmentEvolve = developmentEvolveService.selectDevelopmentEvolveById(developmentEvolveId);
		model.addAttribute("developmentEvolve", developmentEvolve);
	    return prefix + "/edit";
	}
	
	/**
	 * 删除发展发展对象记录
	 */
	@RequiresPermissions("module:developmentEvolve:remove")
	@Log(title = "发展发展对象记录", action = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{
		int rows = developmentEvolveService.deleteDevelopmentEvolveByIds(ids);
		if (rows > 0)
        {
            return success();
        }
        return error();
	}
	
	/**
	 * 文件上传
	 */
	public boolean upload(DevelopmentEvolve developmentEvolve, MultipartFile file, String type){
		boolean success = false;
		try {
			File document = null;
			String fileName = file.getOriginalFilename();  
			File firstFolder = new File(type);
			File secondFolder = new File(firstFolder + "/" + DateUtils.getDate() + "/" + developmentEvolve.getConferenceId());
			if(!firstFolder.exists()){
				firstFolder.mkdirs();
			}
			if(!secondFolder.exists()){
				secondFolder.mkdirs();
			}
			document = new File(secondFolder+"/",fileName);
			System.out.println("文件上传路径"+ document);
	        file.transferTo(document); 
	        success = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return success;
	}
	
	/**
	 * 获取id最大值
	 */
	public Integer getMaxId(){
		List<DevelopmentEvolve> list = developmentEvolveService.selectDevelopmentEvolveList(null);
		Integer maxId = -1;
		for(DevelopmentEvolve a : list){
			if(a.getDevelopmentEvolveId() > maxId){
				maxId = a.getDevelopmentEvolveId();
			}
		}
		return maxId;
	}
	
	/**
	 * id集合转化name集合
	 */
	public List<DevelopmentEvolve> idToNameList(List<DevelopmentEvolve> list){
		for(DevelopmentEvolve c: list){
			String proposerList = c.getActivistList();
			String successList = c.getSuccessList();
			String failList = c.getFailList();
			String proposerName = "";//存放决议姓名名单
			String successName = "";//存放决议通过姓名名单
			String failName = "";//存放决议未通过姓名名单
			Conference conference = conferenceService.selectConferenceById(c.getConferenceId());
			c.setConference(conference);
			//构造决议姓名名单
			if(proposerList == null){
				c.setActivistNameList(null);
			}else{
				String[] pList = proposerList.split(",");
				for(String id : pList){
					User user = userService.selectUserById(Long.valueOf(id));
					proposerName += user.getUserName() + ",";
				}
				c.setActivistNameList(proposerName.substring(0, proposerName.length() - 2));
			}
			
			//构造未通过姓名名单
			if(failList == null){
				c.setFailNameList(null);
			}else{
				String[] fList = failList.split(",");
				for(String id : fList){
					User user = userService.selectUserById(Long.valueOf(id));
					failName += user.getUserName() + ",";
				}
				c.setFailNameList(failName.substring(0, failName.length() - 2));
			}
			
			//构造通过姓名名单
			if(successList == null){
				c.setSuccessNameList(null);
			}else{
				String[] sList = successList.split(",");
				for(String id : sList){
					User user = userService.selectUserById(Long.valueOf(id));
					successName += user.getUserName() + ",";
				}
				c.setSuccessNameList(successName.substring(0, successName.length() - 2));
			}
			
		}
		return list;
	}
	
}
